<template>
  <li class="todo-item">
    <el-tag v-if="!isEditing" type="info">{{ todo }}</el-tag>
    <el-input
      v-else
      v-model="editedTodo"
      @keyup.enter="saveTodo"
      placeholder="请输入新的待办事项..."
      class="edit-input"
    />

    <el-button @click="toggleEdit">
      {{ isEditing ? '取消' : '编辑' }}
    </el-button>
    <el-button @click="saveTodo" v-if="isEditing" type="success">保存</el-button>
    <el-button @click="removeTodo" type="danger">删除</el-button>
  </li>
</template>

<script setup>
import { ref } from 'vue';

// 接收 props
const props = defineProps({
  todo: String,
  index: Number
});

const emit = defineEmits(['remove-todo', 'update-todo']);

const isEditing = ref(false);
const editedTodo = ref(props.todo);

function toggleEdit() {
  isEditing.value = !isEditing.value;
  editedTodo.value = props.todo; // 恢复原始值
}

function saveTodo() {
  if (editedTodo.value.trim()) {
    emit('update-todo', { index: props.index, newTodo: editedTodo.value.trim() });
    isEditing.value = false;
  }
}
function removeTodo() {
  emit('remove-todo', props.index);
}
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.todo-item .edit-input {
  flex-grow: 1;
  margin-right: 10px;
}
.todo-item .el-button {
  margin-left: 8px;
}
</style>